import axios from '@/utils/request'
import { transformSize, fileTypeCorrect } from '@/utils/file/file'
import { baseURL } from '@/utils/request'

const token =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJubmpjZmoiLCJzY29wZSI6WyJiaXpfc3lzIiwiYmlnX3NjcmVlbiIsInNlcnZlciIsImFsbCJdLCJkZXRhaWwiOnsiaWQiOjgzNjkxMzg3Mjg2MzYzNzUwNCwib3JnSWQiOjE1OTI2NDM3NzQsImNvcnBJZCI6bnVsbCwidXNlcm5hbWUiOiJubmpjZmoiLCJyZWFsTmFtZSI6IuWNl-WugeW4guW4guWcuuebkeedo-euoeeQhuWxgCIsInBhc3N3b3JkIjpudWxsLCJlbmFibGVkIjp0cnVlLCJhcmVhSWQiOjQ1MDEwMCwiYXJlYUxldmVsIjoyLCJvcmdUeXBlIjpudWxsLCJvcmdDb2RlIjoiIiwiZm9yZWlnblVzZXJJZCI6bnVsbCwibGV2ZWwiOm51bGwsInBob25lIjoiMTgzNzM4MTY2ODciLCJyb2xlRmxhZyI6MCwidXNlclR5cGUiOjIsInJvbGVDb2RlTGlzdCI6WyJSMDA1Il0sImF1dGhvcml0aWVzIjpbeyJhdXRob3JpdHkiOiJSMDA1In1dLCJhY2NvdW50Tm9uRXhwaXJlZCI6dHJ1ZSwiY3JlZGVudGlhbHNOb25FeHBpcmVkIjp0cnVlLCJhY2NvdW50Tm9uTG9ja2VkIjp0cnVlfSwiZXhwIjoxNjYxNzgwNTI2LCJhdXRob3JpdGllcyI6WyJSMDA1Il0sImp0aSI6ImQyMWYxZTNhLWJiNWMtNDMxZC1iODI0LTc4MTdjZDdhMWMwMSIsImNsaWVudF9pZCI6Im5pcHZ0LWFwcCJ9.UwKREujwIG_9esRoBj5v69y0tTEwfp83BbYzqvApStM'

const useUpload = () => {
  // 上传前钩子函数（uploadMode === 'custom'启用）
  const onBeforeUpload = (file: File, config) => {
    const { allowedFileTypes, maxFileSize } = config
    if (!fileTypeCorrect(file.type, allowedFileTypes)) {
      return {
        correct: false,
        msg: '文件类型错误，请传入正确的文件类型！'
      }
    } else if (file.size > maxFileSize) {
      return {
        correct: false,
        msg: `文件大小超出${transformSize(
          maxFileSize
        )}，请上传规定大小内的文件！`
      }
    }
    return {
      correct: true
    }
  }

  // 自定义上传功能
  const requestUpload = async (file, config) => {
    const { fieldName, server, headers, getAttachmentUrl } = config
    const formData = new FormData()
    formData.append(fieldName, file)
    const res = await axios({
      url: server,
      method: 'post',
      headers: headers,
      data: formData
    })
    const url = getAttachmentUrl(res, config)
    if (!url) throw new Error()
    else return url
  }

  // 上传逻辑入口
  async function customUpload(file: File, insertFn, config) {
    try {
      const { onBeforeUpload, requestUpload, name } = config
      const beforeResult = onBeforeUpload(file, config)
      if (!beforeResult.correct) {
        return window['$message'].warning(beforeResult.msg)
      }
      const url = await requestUpload(file, config)
      if (['图片', '视频'].includes(name)) {
        insertFn(url, '', url)
      } else if (name === '文件') {
        insertFn(file.name, url)
      }
    } catch (err) {
      window['$message'].warning('文件上传失败，请重新上传！')
    }
  }

  // 需要用户根据上传接口返回值，提供真实的获取文件的url
  const getAttachmentUrl = (res, config) => {
    if (res.code === 20000 && res?.data?.data?.sAttachment?.attachPath) {
      const filePath = res.data.data.sAttachment.attachPath
      return `${baseURL}${config.attachmentServer}?token=${token}&pdfPath=${filePath}`
    } else return false
  }

  return {
    getAttachmentUrl,
    onBeforeUpload,
    requestUpload,
    customUpload
  }
}

export default useUpload
